package com.sxj.PDMS.controller.student;

import cn.hutool.core.io.FileUtil;
import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.controller.admin.AdminMessageController;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.model.dto.student.StudentPersonalDataRequest;
import com.sxj.PDMS.service.StudentUploadDataService;
import com.sxj.PDMS.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;

@CrossOrigin
@RestController
@RequestMapping("/student")
@Slf4j
public class StudentPersonalFileController {
    @Autowired
    private StudentUploadDataService studentUploadDataService;

    @PostMapping("/upload_personalData")
    public BaseResponse personalDataUpload(@RequestBody StudentPersonalDataRequest studentPersonalDataRequest) throws IOException, ParseException {
        log.info("文件上传：", studentPersonalDataRequest);
        log.info("个人文件上传：{}", studentPersonalDataRequest);
        if (studentPersonalDataRequest.getStudentNumber() == null || studentPersonalDataRequest.getStudentNumber().trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "学生学号不能为空");
        }
        if (studentPersonalDataRequest.getDataAddress() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
        // todo 文件大小进行限制50mb


        Boolean saved = studentUploadDataService.personalDataUpload(studentPersonalDataRequest);
        if (!saved) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        return Result.success();
    }

    @PostMapping("/upload_personalFile")
    public String uploadPersonalFile(@RequestPart(value = "uploadFile") MultipartFile uploadFile) {
        log.info("文件上传：{}", uploadFile);
        if (uploadFile != null && !uploadFile.isEmpty()) {
            synchronized (StudentPersonalFileController.class) {
                //获取当前时间戳
                String flag = System.currentTimeMillis() + "";
                //获取文件名
                String fileName = uploadFile.getOriginalFilename();
                try {
                    //todo：/管理员提交personalFile的存放路径
                    String path = "D:\\user\\Desktop\\store\\student_files\\";
                    FileUtil.writeBytes(uploadFile.getBytes(), path + "\\" + flag + "-" + fileName);
                    System.out.println(fileName + "上传成功");
                    Thread.sleep(1L);
                } catch (Exception e) {
                    System.out.println(fileName + "上传失败");
                }
                return flag;
            }
        } else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
    }
}
